package com.woniuxy.woniufp.system.mqlistener;

import com.rabbitmq.client.Channel;
import com.woniuxy.woniufp.common.model.constant.MQConstant;
import com.woniuxy.woniufp.common.model.dto.bank.BankCardRequestDto;
import com.woniuxy.woniufp.system.entity.UserDetail;
import com.woniuxy.woniufp.system.service.IUserCardService;
import com.woniuxy.woniufp.system.service.IUserDetailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;


@Component
@Slf4j
public class BindResultConsumer {

    @Autowired
    IUserDetailService userDetailService;

    @Autowired
    IUserCardService userCardService ;

    /**
     * 监听队列woniufp-queue-account的消息
     *
     * @Payload 注解
     * 1、注解实现把消息的json内容转换为对象
     * 2、注意：要配置消息的转换器
     * A.更新用户详情绑卡状态
     * B.更新用户绑卡信息表; u_user_card
     */
    @RabbitListener(queues = MQConstant.WONIUFP_QUEUE_ACCOUNT)
    public void handlerMsg(@Payload BankCardRequestDto bankCardRequestDto , Message message, Channel channel) throws IOException {
        log.info("MQ监听到消息：{}",bankCardRequestDto);
        try {
            //更新 用户的绑卡状态
            userDetailService.modifyUserDetailOfStatusByReqCode(bankCardRequestDto.getReqCode(), 1);
            //更新托管代理中心的 同步状态
            UserDetail userDetail = userDetailService.findUserDetailByReqCode(bankCardRequestDto.getReqCode());
            userCardService.modifyBankInfoByUserId(userDetail.getId(), bankCardRequestDto.getBankNo(), bankCardRequestDto.getBankTitle());
            /*
              手动 回复
              message.getMessageProperties().getDeliveryTag() ：获取 最后一个消息的序号
              true  : 批量回复  比当前序号小的消息 全部回复  false ：只回复当前消息

             */
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            log.info("消息处理成功,{}",bankCardRequestDto);
        }catch (Exception e) {
            e.printStackTrace();
            //退回消息，将消息重新放回队列
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
            log.info("消息处理失败,{}",bankCardRequestDto);
        }
    }
}
